﻿using System;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Com.CodePlex.SPC3.ProfileImageUpload {

	public static class Ext {

		public static string CombineUrl(this string uri1, string uri2) { 
			uri1 = uri1.TrimEnd('/'); 
			uri2 = uri2.TrimStart('/'); 
			return string.Format("{0}/{1}", uri1, uri2); 
		} 

		public static System.Windows.Forms.IWin32Window GetIWin32Window(this System.Windows.Media.Visual visual) {
			var source = System.Windows.PresentationSource.FromVisual(visual) as System.Windows.Interop.HwndSource;
			System.Windows.Forms.IWin32Window win = new OldWindow(source.Handle);
			return win;
		}

		private class OldWindow : System.Windows.Forms.IWin32Window {
			private readonly System.IntPtr _handle;
			public OldWindow(System.IntPtr handle) {
				_handle = handle;
			}
			System.IntPtr System.Windows.Forms.IWin32Window.Handle {
				get { return _handle; }
			}
		}

		public static byte[] ResizeImage(string filename, int width, int height) {
			using (Bitmap image = new Bitmap(filename)) {
				ImageFormat loFormat = image.RawFormat;
				decimal ratio;
				int width2 = 0;
				int height2 = 0;
				if (image.Width < width && image.Height < height) {
					return File.ReadAllBytes(filename);
				} else {
					if (image.Width > image.Height) {
						ratio = (decimal)(1.0 * width / image.Width);
						width2 = width;
						decimal lnTemp = image.Height * ratio;
						height2 = (int)lnTemp;
					} else {
						ratio = (decimal)(1.0 * height / image.Height);
						height2 = height;
						decimal lnTemp = image.Width * ratio;
						width2 = (int)lnTemp;
					}
					Bitmap image2 = new Bitmap(width2, height2);
					Graphics g = Graphics.FromImage(image2);
					g.InterpolationMode = InterpolationMode.HighQualityBicubic;
					g.FillRectangle(Brushes.White, 0, 0, width2, height2);
					g.DrawImage(image, 0, 0, width2, height2);
					MemoryStream ms = new MemoryStream();
					//image2.Save(ms, ImageFormat.Jpeg);
					image2.Save(ms, loFormat);
					ms.Position = 0;
					byte[] data = new byte[ms.Length];
					ms.Read(data, 0, (int)ms.Length);
					return data;
				}
			}
		}
	}
}
